/*----------------------------------------------------------------------------
Owner(s): Shane Whitfield
$Copyright: $
$Id: $
----------------------------------------------------------------------------*/

#include "go_playerweapons.h"
#include "timermgr.h"
#include "gomgr.h"
#include "render.h"

/*--------------------------------------------------------------------------*/

CGoWeaponBasic::CGoWeaponBasic()
{
	SetConstructionTime(1.5f);
	SetBoundingRadius(0.2f);
	setProvidesConnection(false);
	
	m_attackRange = 1.0f;
	m_state = EState_WaitingConstruction;
	m_tState = T();
	m_target = NULL;
	
	SetTexture("weapon_basic.png");
}

void CGoWeaponBasic::Render()
{
	super::Render();
	
	if (m_state == EState_Attacking)
	{
		BasicDrawObjects::DrawSegment(GetPos(), m_target->GetPos(), Color3f(1.0f, 0.5f, 0.5f));
	}
}

void CGoWeaponBasic::Update()
{
	super::Update();
	
	for (;;)
	{
		EState prevState = m_state;
		
		switch(m_state)
		{
		case EState_WaitingForConnection:
			{
				if (IsConnected())
				{
					setState(EState_SeekingTarget);
				}
			}
			break;
		default:
			{
				if (!IsConnected())
				{
					setState(EState_WaitingForConnection);
				}
			}
			break;
		}
		
		switch(m_state)
		{
		case EState_WaitingConstruction:
			{
				if (IsPlaced() && IsConstructed())
				{
					setState(EState_WaitingForConnection);
				}
			}
			break;
		case EState_SeekingTarget:
			{
				//did we find a target?
				if (m_target)
				{
					setState(EState_Attacking);
				}
				else
				{
					setState(EState_WaitingFindTargetPing);
				}
			}
			break;
		case EState_WaitingFindTargetPing:
			{
				if ((T() - m_tState) >= 0.2)
				{
					setState(EState_SeekingTarget);
				}

			}
			break;
		case EState_RechargingAttack:
			{
				if ((T() - m_tState) >= 1.0)
				{
					setState(EState_Attacking);
				}
			}
			break;
		case EState_Attacking:
			{
				if (!m_target || m_target->IsDead() ||
					(Dist(m_target->GetPos(), GetPos()) > m_attackRange))
				{
					setState(EState_SeekingTarget);
				}
				else if ((T() - m_tState) >= 0.3)
				{
					setState(EState_RechargingAttack);
				}
				else
				{
					m_target->Damage(50.0f * Dt());
				}
			}
			break;
		}
		
		if (prevState == m_state)
		{
			break;
		}
	}
}

void CGoWeaponBasic::setState(EState i_state)
{
	m_state = i_state;
	m_tState = T();
	
	switch(m_state)
	{
	case EState_SeekingTarget:
		{
			m_target = findNextTarget();
		}
		break;
	}
}

CGo* CGoWeaponBasic::findNextTarget()
{
	//get the target closest to us?
	std::vector<CGo*> m_foundTargets;
	g_gomgr.GetNearEnemies(GetPos(), m_attackRange , m_foundTargets);
	
	CGo* selectedTarget = NULL;
	for (int iTarget = 0; iTarget < m_foundTargets.size(); ++iTarget)
	{
		CGo* target = m_foundTargets[iTarget];
		if (target != this && target->IsAlive())
		{
			selectedTarget = target;
			break;
		}
	}
	
	return selectedTarget;
}

/*-----------------------------------EOF!-----------------------------------*/ 
